package com.power.handler;

import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import com.power.constant.Constant;
import com.power.model.TUser;
import com.power.result.R;
import com.power.service.RedisService;
import com.power.util.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @Author 海晨忆
 * @Des 登录成功回调
 * @Date 2025/8/7 9:08
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private RedisService redisService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //生成JWT
        TUser tUser = (TUser) authentication.getPrincipal();
        String userJson = JSONUtil.toJsonStr(tUser);
        String token = JWTUtil.createToken(Map.of("user", userJson), Constant.LOGIN_JWT_SECRET.getBytes(StandardCharsets.UTF_8));
        //把token写入redis
//        redisTemplate.opsForValue();//字符串类型
//        redisTemplate.opsForHash();//Hash类型
//        redisTemplate.opsForSet();//set类型
//        redisTemplate.opsForZSet();//zset类型
//        redisTemplate.opsForList();//list类型
//        redisTemplate.opsForHash().put(Constant.REDIS_TOKEN_KEY, String.valueOf(tUser.getId()), token);
//        String redisToken = (String) redisTemplate.opsForHash().get(Constant.REDIS_TOKEN_KEY, tUser.getId());
        redisService.setValue(Constant.REDIS_TOKEN_KEY + tUser.getId(), token);
        redisService.expire(Constant.REDIS_TOKEN_KEY + tUser.getId(), 30 * 60L);//30分钟过期
        R result = R.OK("登录成功", token);
        //数据转json字符串
        String jsonStr = JSONUtil.toJsonStr(result);
        //把数据写给前端
        ResponseUtils.write(response, jsonStr);
    }
}
